package com.desay.pangoo.itmt.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.desay.pangoo.common.lite.lang.web.BusinessException;
import com.desay.pangoo.common.lite.lang.web.PangooWebConstant;
import com.desay.pangoo.common.lite.spring.web.ControllerCommonUtils;
import com.desay.pangoo.itmt.controller.vo.ProjectBUVo;
import com.desay.pangoo.itmt.entity.BUDivEntity;
import com.desay.pangoo.itmt.entity.ProjectBUEntity;
import com.desay.pangoo.itmt.enums.ExceptionCodeEnum;
import com.desay.pangoo.itmt.repository.BUDivRepository;
import com.desay.pangoo.itmt.repository.ProjectBURepository;
import com.desay.pangoo.itmt.repository.spec.ExpandCriteria;
import com.desay.pangoo.itmt.repository.spec.Restrictions;
import com.desay.pangoo.itmt.service.ProjectBuService;

import cn.hutool.core.collection.CollUtil;

/**
 * @author uidq1163
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProjectBuServiceImpl implements ProjectBuService {

	@Autowired
	private BUDivRepository bUDivRepository;
	@Autowired
	private ProjectBURepository projectBURepository;

	@Override
	public Long create(ProjectBUVo vo) {
		String user = ControllerCommonUtils.getHeader(PangooWebConstant.HEADER_NAME_USER_FULL_NAME);
		ProjectBUEntity projectBUEntity = new ProjectBUEntity();
		BeanUtils.copyProperties(vo, projectBUEntity);
		projectBUEntity.setCreator(user);
		if (CollUtil.isNotEmpty(vo.getBuIds())) {
			Set<BUDivEntity> bus = vo.getBuIds().stream().map(b -> {
				Optional<BUDivEntity> exist = bUDivRepository.findById(b);
				if (!exist.isPresent()) {
					throw new BusinessException(ExceptionCodeEnum.BU_NOT_EXIST);
				}
				return exist.get();
			}).collect(Collectors.toSet());
			projectBUEntity.setBus(bus);
		}
		projectBUEntity
				.setProductPlatform(projectBUEntity.getPlatform() + ":" + projectBUEntity.getPlatformClassification());
		projectBURepository.save(projectBUEntity);
		return projectBUEntity.getId();
	}

	@Override
	public void delete(Long id) {
		Optional<ProjectBUEntity> opiton = projectBURepository.findById(id);
		if (!opiton.isPresent()) {
			throw new BusinessException(ExceptionCodeEnum.PROJECT_BU_NOT_EXIST);
		}
		// 删除关联表数据
		projectBURepository.deleteRefProjectPlatformByBuId(id);
		projectBURepository.deleteById(id);
	}

	@Override
	public void update(Long id, ProjectBUVo vo) {
		String user = ControllerCommonUtils.getHeader(PangooWebConstant.HEADER_NAME_USER_FULL_NAME);
		ExpandCriteria<ProjectBUEntity> c = new ExpandCriteria<>();
		c.add(Restrictions.eq("platform", vo.getPlatform(), true));
		c.add(Restrictions.eq("platformClassification", vo.getPlatformClassification(), true));
		c.add(Restrictions.ne("id", id, true));
		List<ProjectBUEntity> list = projectBURepository.findAll(c);
		if (CollUtil.isNotEmpty(list)) {
			throw new BusinessException(ExceptionCodeEnum.PROJECT_BU_HAS_EXIST);
		}
		Optional<ProjectBUEntity> optional = projectBURepository.findById(id);
		if (!optional.isPresent()) {
			throw new BusinessException(ExceptionCodeEnum.PROJECT_BU_NOT_EXIST);
		}
		ProjectBUEntity existEntity = optional.get();
		BeanUtils.copyProperties(vo, existEntity, "id");
		if (CollUtil.isNotEmpty(vo.getBuIds())) {
			Set<BUDivEntity> bus = vo.getBuIds().stream().map(b -> {
				Optional<BUDivEntity> exist = bUDivRepository.findById(b);
				if (!exist.isPresent()) {
					throw new BusinessException(ExceptionCodeEnum.BU_NOT_EXIST);
				}
				return exist.get();
			}).collect(Collectors.toSet());
			existEntity.setBus(bus);
		} else {
			existEntity.setBus(null);
		}
		existEntity.setProductPlatform(existEntity.getPlatform() + "：" + existEntity.getPlatformClassification());
		existEntity.setUpdator(user);
		projectBURepository.save(existEntity);
	}

	@Override
	public Page<ProjectBUEntity> getAll(String platform, String platformClassification, Integer pageSize,
			Integer pageNum) {
		ExpandCriteria<ProjectBUEntity> c = new ExpandCriteria<>();
		// 根据组查询
		c.add(Restrictions.like("platform", platform, true));
		// 根据组查询
		c.add(Restrictions.like("platformClassification", platformClassification, true));
		List<Order> orders = new ArrayList<>();
		Order order = new Order(Sort.Direction.DESC, "createTime");
		orders.add(order);
		Pageable pageReq = PageRequest.of(pageNum - 1, pageSize, Sort.by(orders));
		return projectBURepository.findAll(c, pageReq);
	}
}
